package com.woniuxy.vuecli.controller;

import com.woniuxy.vuecli.entity.EmailCode;
import com.woniuxy.vuecli.entity.ResponseResult;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author author
 * @Create 2024-01-15 10:09
 */
//@CrossOrigin
@RequestMapping("/email")
@RestController
public class EmailController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @RequestMapping("/send/{email}")
    public ResponseResult send(@PathVariable("email")String email){
        //调用Service：如果当前邮箱没有被注册过，抛异常
        //产生验证码
        String code = UUID.randomUUID().toString().substring(0, 4);
        //验证码存到Redis中,使用email作为key
        redisTemplate.opsForValue().set("emailcode:"+email, code, 30, TimeUnit.SECONDS);
        //发送邮件
//        MailUtil.send(email, "xxx网站找回密码", "找回密码邮箱验证码:"+code,false);
        //邮件发送：引入MQ解耦，向队列发送消息，让消费者执行发邮件
        rabbitTemplate.convertAndSend("exchangetopic", "email", new EmailCode(email,code));
        return new ResponseResult<>(200,"邮件发送ok",null);
    }
}
